<template>
  <div>
    <avue-crud :option="option"
               :data="tableData">
      <template slot="menuRight">
        <el-tooltip :enterable="false"
                    placement="top"
                    :content="$t('common.save')">
          <el-button icon="el-icon-check"
                     type="primary"
                     size="small"
                     v-if="show"
                     @click="saveData"></el-button>
        </el-tooltip>
      </template>
      <template slot="index"
                slot-scope="{row}">
        <el-tooltip :enterable="false"
                    v-if="row.$index === tableData.length - 1"
                    placement="top"
                    :content="$t('common.add')">
          <el-button icon="el-icon-plus"
                     @click="getClassByTableName"
                     type="text"  v-if="show"></el-button>
        </el-tooltip>
        <el-tooltip :enterable="false"
                    placement="top"
                    :content="$t('common.delete')"  v-if="show">
          <el-button icon="el-icon-delete"
                     @click="delRow(row)"
                     type="text"></el-button>
        </el-tooltip>
      </template>
      <template slot="expand"
                slot-scope="scope">
        <el-tabs type="border-card">
          <template v-for="item in labelList">
            <el-tab-pane v-if="scope.row.characterDataList.filter(res=>res.labelId === item.id).length !== 0"
                         :label="item.label"
                         :key="item.id"
                         class="tab-content">
              <avue-crud :class="{hideTitle:!!factoryId}"
                         :option="exOption"
                         :data="scope.row.characterDataList.filter(res=>res.labelId === item.id)">
                <template slot="menuRight">
                  <el-tooltip :enterable="false"
                              placement="top"
                              :content="$t('common.simulation')">
                    <el-button type="primary"
                               icon="el-icon-view"
                               size="small"
                               @click="openBomView(scope.row.characterDataList)"></el-button>
                  </el-tooltip>
                </template>
                <template slot="fieldName"
                          slot-scope="{row}">
                  <span :class="{'isRequired':row.isRequired}">{{row.fieldName}}</span>
                </template>
                <template slot="fieldVal"
                          slot-scope="{row}">
                  <customFieldsToClass v-if="!!scope.row.isVariant"
                                       v-model="row.fieldVal"
                                       @change="(value)=>{changeValue(row,value)}"
                                       :form="row"
                                       :checkData="scope.row.characterDataList"
                                       :checkRules="scope.row.checkRules"
                                       :configRules="scope.row.configRules"
                                       :validTime="scope.row.validTime"
                                       :isValid="true"
                                       :isDefault="false"></customFieldsToClass>
                  <customFieldsToClass v-else
                                       v-model="row.fieldVal"
                                       @change="(value)=>{changeValue(row,value)}"
                                       :form="row"></customFieldsToClass>
                </template>
              </avue-crud>
            </el-tab-pane>
          </template>
        </el-tabs>
      </template>
      <template slot="filePath"
                slot-scope="{row}">
        <span v-if="!row.filePath">暂无图片</span>
        <el-image v-else
                  :src="row.filePath"
                  fit="fill"
                  :preview-src-list="[row.filePath]"></el-image>
      </template>
    </avue-crud>
    <el-dialog :title="$t('common.add')+$t('empTypeTree.classify')"
               :visible.sync="classVisible"
               width="50%"
               :before-close="closeClass">
      <avue-crud class="classTable"
                 :option="classOption"
                 :data="classList"
                 @current-row-change="changeRow"></avue-crud>
      <span slot="footer"
            class="dialog-footer">
        <!--<el-button @click="closeClass">{{$t('common.cancel')}}</el-button>
        <el-button type="primary"
                   @click="closeClass(true)">{{$t('common.save')}}</el-button>
-->
        <el-tooltip :content="$t('common.save')" placement="top">
          <el-button type="primary" @click.stop="closeClass(true)" size="mini" class="iconfont iconcheck"></el-button>
        </el-tooltip>
        <el-tooltip :content="$t('common.cancel')" placement="top">
          <el-button @click.stop="closeClass" size="mini" class="iconfont iconclose"></el-button>
        </el-tooltip>
      </span>
    </el-dialog>
    <el-dialog v-if="!validatenull(bomViewData) && bomViewVisible"
               title="BOM查看"
               width="50%"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :before-close="close"
               :visible.sync="bomViewVisible">
      <bomView ref="bomView"
               :root="bomViewData"
               :productId="objectId"
               :factoryId="factoryId"></bomView>
      <span slot="footer"
            class="dialog-footer">

        <el-tooltip :enterable="false"
                    placement="top"
                    :content="$t('common.confirm')">
          <el-button icon="el-icon-check"
                     type="primary"
                     @click="close"></el-button>
        </el-tooltip>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { option, exOption, classOption } from './materialViewClass'
import { remote } from '../../api/admin/dict'
import { getClassByTableName, addClass, removeClass, saveClassCharacter, getClassCharacter } from '../../api/setting/classProperties'
import customFieldsToClass from '../../components/customFieldsToClass'
import bomView from '../../components/bomView'
import { getVariantTableClassId, getCharacterConfigureClassId, checkConfigure, getOperator } from '../../api/setting/productSelection'

export default {
  components: { customFieldsToClass, bomView },
  props: {
    tableName: {
      required: true,
      type: String,
      remark: '<span class="required-remark">*</span> 业务资源实体的表名',
      values: ''
    },
    show:{
      type:Boolean,
      default:true
    },
    objectId: {
      type: [Number, String],
      required: true,
      remark: '<span class="required-remark">*</span> 当前业务对象的主键id',
      values: ''
    },
    factoryId: {
      type: Number,
      default: -1,
      remark: '工厂id',
      values: ''
    },
    orgId: {
      type: Number,
      default: 0,
      remark: '所属组织id',
    }
  },
  data () {
    return {
      option: option(this),
      exOption: exOption(this),
      classOption: classOption(this),
      tableData: [],
      labelList: [],
      classList: [],
      classVisible: false,
      currentRow: {},
      bomViewVisible: false,
      bomViewData: [],
    }
  },
  watch: {
    tableName () {
      this.getClassCharacter()
    },
    objectId () {
      this.getClassCharacter()
    }
  },
  mounted () {
    this.getClassCharacter()
    this.getClassLabel()
    this.getDict()
  },
  methods: {
    openBomView (data) {
      if (!this.factoryId) return
      this.bomViewData = data.map(res => {
        return {
          characterId: res.characterId,
          fieldName: res.fieldName,
          val: res.fieldVal
        }
      })
      this.bomViewVisible = true
    },
    close () {
      this.bomViewVisible = false
    },
    changeValue (row, value) {
      this.tableData.some(res => {
        if (!!res.isVariant) res.validTime = new Date().getTime()
        res.characterDataList.some(res2 => {
          if (res2.characterId === row.characterId) res2.fieldVal = row.fieldVal
        })
      })
      if (value && row.fieldType === 'ComboBox') row = { ...row, ...value }
    },
    getClassCharacter () {
      let parmas = 0
      let index = 0
      getClassCharacter(this.objectId, this.tableName, 0).then(res => {
        const data = res.data.data
        this.tableData = data.length > 0 ? data : [{ id: -1, characterDataList: [{}] }]
        const parseData = (index = 0) => {
          if (!this.tableData[index]) return
          if (!!this.tableData[index].isVariant) getVariantTableClassId(this.tableData[index].id).then(res => {
            const data = res.data.data
            const result = []
            data.some(res2 => {
              const order = res2.fieldList.map(res => res.characterId)
              res2.rowList.some(res3 => {
                const item = {}
                order.some((res4, index) => {
                  item[res4] = res3[index]
                })
                result.push(item)
              })
            })
            this.tableData[index].checkRules = result
            return getCharacterConfigureClassId(this.tableData[index].id)
          }).then(res => {
            if (res.data.data.length > 0) this.tableData[index].configRules = res.data.data.map(res => res.characterConfigureList).reduce((pre, next) => { return pre.concat(next) })
            else this.tableData[index].configRules = []
            parseData(++index)
          })
          else parseData(++index)
        }
        parseData()
        this.$emit('loadOk')
      })
    },
    getClassByTableName () {
      getClassByTableName(this.tableName).then(res => {
        this.classList = res.data.data
        this.classVisible = true
      })
    },
    getClassLabel () {
      remote({ paramId: 'sys_class_label', orgId: this.orgId || this.$store.getters.userInfo.orgId }).then(res => {
        this.labelList = res.data.data
      })
    },
    delRow (row) {
      removeClass(row.id, this.objectId, this.tableName).then(res => {
        this.$message({
          type: res.data.meta.success ? "success" : "error",
          message: res.data.meta.message,
        });
        this.getClassCharacter()
      })
    },
    changeRow (row) {
      this.currentRow = row
    },
    closeClass (flag) {
      if (flag === true) {
        addClass(this.currentRow.id, this.objectId, this.tableName).then(res => {
          this.$message({
            type: res.data.meta.success ? "success" : "error",
            message: res.data.meta.message,
          });
          this.getClassCharacter()
        })
      }
      this.classVisible = false
    },
    getDict () {
      getOperator().then(res => {
        this.operators = res.data.data
      })
    },
    getOperatorName (operator) {
      let result = ''
      this.operators.some(res => {
        if (operator === res.code) {
          result = res.name
          return true
        }
      })
      return result
    },
    saveData () {
      let flag = false
      let m1 = ''
      const checkData = (index = 0) => {
        return new Promise((resolve, reject) => {
          if (flag || !this.tableData[index]) {
            console.log(flag, this.tableData[index], index)
            resolve(true)
            return
          }
          this.tableData[index].characterDataList.some(res2 => {
            if (res2.isRequired && !res2.fieldVal) {
              flag = true
              m1 = this.$t('tips.checkRequired')
              return true
            }
          })
          if (this.tableData[index].isVariant) {
            if (!flag) checkConfigure(this.tableData[index].characterDataList.map(res => {
              return {
                characterId: res.characterId,
                fieldName: res.fieldName,
                val: res.fieldVal
              }
            }), this.tableData[index].id).then(res => {
              const data = res.data.data
              const characterIds = this.tableData[index].characterDataList.map(res => res.characterId)
              this.tableData[index].characterDataList.some(res => {
                let message = []
                data.resultList.some(res2 => {
                  if (res2.characterId === res.characterId) {
                    message.push(`${res.fieldName}应${this.getOperatorName(res2.operator)}${res2.attributeValue}`)
                    return true
                  }
                })
                if (data.returnCharacterIdList && data.returnCharacterIdList.indexOf(res.characterId) !== -1) message.push(res.fieldName + '不符合变式表相关性')
                flag = message.length > 0
                m1 = message.join('  |  ')
                checkData(++index).then(res => {
                  resolve(res)
                })
              })
            })
            else {
              resolve(true)
              return
            }
          }
          else if (!flag) checkData(++index).then(res => {
            resolve(res)
          })
          else resolve(true)
        })
      }
      checkData().then(res => {
        if (flag) {
          this.$message.warning(m1)
          return
        }
        saveClassCharacter(this.tableData).then(res => {
          this.$message({
            type: res.data.meta.success ? "success" : "error",
            message: res.data.meta.message,
          });
          this.getClassCharacter()
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.classTable,
.hideTitle {
  /deep/.avue-crud__menu {
    display: none;
  }
}
.isRequired {
  &::before {
    content: "*";
    color: red;
    font-size: 18px;
  }
}
.tab-content {
  height: 200px;
  overflow: auto;
}
/deep/.el-image-viewer__btn {
  color: #fff;
  font-size: 50px !important;
}
</style>
